<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-11-14
 * Time: 14:35
 */

namespace app\common\model;


use app\admin\model\ShopExpressCompany;

class OrderExpress extends BaseModel
{
    protected $autoWriteTimestamp = false;

    public function setLogisticsInformationAttr($value, $data)
    {
        if (empty($value)) {
            return json_encode([], JSON_UNESCAPED_UNICODE);
        } else {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
    }

    public function getLogisticsInformationAttr($value, $data)
    {
        if (empty($value)) {
            return [];
        } else {
            return json_decode($value, true);
        }
    }

    public function shopOrder()
    {
        return $this->belongsTo('Order','order_id','id');
    }

    public function expressCompany()
    {
        return $this->belongsTo('\\app\\admin\\model\\ShopExpressCompany','express_company_id','id');
    }

    /**
     * 根据快递单号更新订单快递信息
     * @param $express_no
     * @param $data
     * @param bool $is_update_company
     */
    public static function updateDataWithExpressNo($express_no, $data, $is_update_company = false)
    {
        $express = static::where([['express_no','=',$express_no]])
            ->find();

        if (empty($express)) {
            throw new \Exception('[订单快递信息]更新订单快递信息失败，查找订单快递失败');
        }

        $update_data = [
            'logistics_information' => empty($data['logistics_information']) ? $express->logistics_information : $data['logistics_information'],
            'express_status' => $data['express_status']
        ];

        if ($is_update_company) {
            // 如果需要更新快递公司信息，则先查找出对应的id
            $express_company = ShopExpressCompany::where([['code','=',$data['new_company']]])
                ->field('id,code')
                ->find();
            if (empty($express_company)) {
                throw new \Exception('[订单快递信息]更新订单快递公司信息失败，查找快递公司失败');
            }
            $update_data['express_company_id'] = $express_company->id;
        }

        $express->allowField(['express_company_id','logistics_information','express_status'])
            ->save($update_data);
    }
}